#!/usr/bin/python3
'''
Copyright 2019 Broadcom. The term "Broadcom" refers to Broadcom Inc.
and/or its subsidiaries.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''

import sys
import time
import os
import json
import signal

from ztp.ZTPLib import getField, updateActivity, systemReboot
message_file = None

def signal_handler(signum, frame):
    '''!
    This signal handler is called on SIGTERM or SIGINT
    '''
    global message_file
    if message_file is not None and os.path.isfile(message_file):
         os.remove(message_file)
    sys.exit(0)

def main():

    # Register signal handlers
    global message_file

    signal.signal(signal.SIGTERM, signal_handler)
    signal.signal(signal.SIGINT, signal_handler)

    try:
        with open(sys.argv[1]) as json_file:
                _json_dict = json.load(json_file)
                json_file.close()
    except IOError as e:
        raise Exception(e)
    except ValueError as e:
        raise Exception('Error in file %s: %s' % (sys.argv[1], e))

    keys = _json_dict.keys()
    if len(keys) == 0:
        print('Invalid section name provided')
        sys.exit(1)
    section_name = next(iter(keys))
    section_data = _json_dict.get(section_name)
    exit_code = 0

    _message = getField(section_data, 'message', str, None)
    message_file = getField(section_data, 'message-file', str, None)
    if _message is not None:
      if message_file is not None:
        os.system ('echo ' + _message + ' >> ' + message_file)
      else:
        print (_message)
  
    _sleep = getField(section_data, 'sleep', int, 0)
    if _sleep > 0:
       updateActivity('test-plugin: sleeping for %d seconds' % _sleep)
       time.sleep(_sleep)

    _reboot_in_between = getField(section_data, 'reboot-in-between', bool , False)
    if _reboot_in_between:
       systemReboot()

    _attempts = getField(section_data, 'attempts', int , None)
    _suspend_exit_code = getField(section_data, 'suspend-exit-code', int , None)
    if _attempts is not None and \
       _suspend_exit_code is not None :
      attempts = _attempts
      exit_code = _suspend_exit_code
      if attempts != 0 :
        attempts = attempts - 1
        section_data['attempts'] = attempts
        with open(sys.argv[1], "w") as json_file:
            json.dump(_json_dict, json_file, indent=4, sort_keys=True)
            json_file.flush()
            json_file.close()
        sys.exit(exit_code)

    _fail = getField(section_data, 'fail', bool , False)
    if _fail:
      sys.exit(exit_code + 1)

    sys.exit(0)
if __name__== "__main__":
   main()
